#! /usr/bin/env bash
. ./scripts/devcontainer/_assert-in-container "$0" "$@"

set -euo pipefail

TOKEN="${GITHUB_RELEASES_TOKEN}"
OWNER="darklang"
REPO="dark"
TAG="v0.0.1"
TARGET_COMMITISH="main"
NAME="cli-pre-release"
BODY="Pre-release of darklang executable"

# Regex pattern to match release tags (e.g. v0.0.1)
release_tag_pattern="^v[0-9]+\.[0-9]+\.[0-9]+$"

# Function to delete a release by ID
delete_release() {
  release_id=$1
  echo "Deleting release: $release_id"
  curl -s -L \
    -X DELETE \
    -H "Accept: application/vnd.github+json" \
    -H "Authorization: Bearer $TOKEN" \
    -H "X-GitHub-Api-Version: 2022-11-28" \
    "https://api.github.com/repos/$OWNER/$REPO/releases/$release_id"
}

# Function to delete a tag
delete_tag() {
  tag_name=$1
  echo "Deleting tag: $tag_name"
  curl -s -L \
    -X DELETE \
    -H "Authorization: Bearer $TOKEN" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
    "https://api.github.com/repos/$OWNER/$REPO/git/refs/tags/$tag_name"
}

# Function to increment the tag number for a new release
increment_tag() {
  ## Fetch latest release tag
  latest_tag=$(curl -s "https://api.github.com/repos/$OWNER/$REPO/releases" | jq -r '.[0].tag_name')

  ## Check id latest tag is empty or null, if no tags found, start from v0.0.1
  if [ -z $latest_tag ] || [ $latest_tag = "null" ]; then
    echo "v0.0.1"
  else
    ## Major.Minor.Patch
    IFS='.' read -r -a version_numbers <<< "$latest_tag"
    major_number=${version_numbers[0]}
    minor_number=${version_numbers[1]}
    patch_number=${version_numbers[2]}
    patch_number=$((patch_number + 1))
    echo "${major_number}.${minor_number}.${patch_number}"
  fi
}

TAG=$(increment_tag)


# Create a GitHub release
response=$(curl -s -L \
  -X POST \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer $TOKEN" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  "https://api.github.com/repos/$OWNER/$REPO/releases" \
  -d "{\"tag_name\":\"$TAG\",\"target_commitish\":\"$TARGET_COMMITISH\",\"name\":\"$NAME\",\"body\":\"$BODY\",\"draft\":false,\"prerelease\":true,\"generate_release_notes\":false}")

echo "Release creation response: $response"

# Store the new release ID to delete the release if files upload fails
new_release_id=$(echo $response | jq -r '.id')

## Check if release creation was successful
if [ "$(echo "$response" | jq -r '.id')" == "null" ]; then
  echo "Release creation failed"
  exit 1
fi


# Upload files to the release

## Extract the upload URL from the response: remove the {?name,label} part
upload_url=$(echo $response | jq -r .upload_url | sed -e "s/{?name,label}//")

## Upload all files in the clis directory
FILES_DIR="/home/dark/app/clis"
FILES_FOUND=false

for FILE_PATH in "$FILES_DIR"/*; do
  if [[ -f "$FILE_PATH" ]]; then
    FILES_FOUND=true
    FILE_NAME=$(basename "$FILE_PATH")
    echo "Uploading file: $FILE_PATH"

    upload_response=$(curl -s -L \
        -X POST \
        -H "Accept: application/vnd.github+json" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/octet-stream" \
        "$upload_url?name=$FILE_NAME" \
        --data-binary @"$FILE_PATH")
  fi
done


# Check if all executables uploaded successfully before deleting old releases
if [ "$FILES_FOUND" = false ] || [ "$(echo "$upload_response" | jq -r '.state')" != "uploaded" ]; then
    echo "Not all executables uploaded successfully."
    echo "Deleting the newly created release..."
    delete_release "$new_release_id"
    echo "Deleting the tag..."
    delete_tag "$TAG"
    echo "Deleted"
    exit 1
else
    echo "All executables uploaded successfully"
fi

# Delete old releases

## List all releases
list_releases_response=$(curl -s -L \
  -X GET \
  -H "Authorization: Bearer $TOKEN" \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  "https://api.github.com/repos/$OWNER/$REPO/releases")

## Extract release IDs
release_ids=$(echo $list_releases_response | jq -r '.[].id')

## Extract the new release ID
new_release_id=$(echo $response | jq -r '.id')

## Loop through all release IDs and delete them, except the new release
for release_id in $release_ids; do
  if [ "$release_id" != "$new_release_id" ]; then
    # Fetch the tag name associated with the release
    tag_name=$(curl -s -L \
        -X GET \
        -H "Authorization: Bearer $TOKEN" \
        -H "Accept: application/vnd.github+json" \
        -H "X-GitHub-Api-Version: 2022-11-28" \
        "https://api.github.com/repos/$OWNER/$REPO/releases/$release_id" | jq -r '.tag_name')

    # Check if tag name is valid
    if [ -n "$tag_name" ] && [ "$tag_name" != "null" ] && [[ $tag_name =~ $release_tag_pattern ]]; then
      delete_release "$release_id"

      # Check if the release was successfully deleted
      release_exists=$(curl -s -L \
          -X GET \
          -H "Authorization: Bearer $TOKEN" \
          -H "Accept: application/vnd.github+json" \
          -H "X-GitHub-Api-Version: 2022-11-28" \
          "https://api.github.com/repos/$OWNER/$REPO/releases/$release_id" | jq -r '.id')

      if [ "$release_exists" = "null" ]; then
        delete_tag "$tag_name"
      else
        echo "Failed to delete release: $release_id, skipping tag deletion"
        exit 1
      fi
    else
      echo "Failed to fetch tag name for release: $release_id, skipping release deletion"
      exit 1
    fi
  fi
done

echo "Old releases deleted"
